<?php

require 'common.php';

switch(@$_REQUEST['action']){
	case 'add_addressbook_entry': // {
		$js='';
		$errors=array();
		// { check name
		$name=$_REQUEST['name'];
		if($name=='')$errors[]="Name must be entered";
		// }
		if(!count($errors)){
			$name=addslashes($name);
			$languages=addslashes(@$_REQUEST['languages']);
			$notes=addslashes(@$_REQUEST['notes']);
			$address=addslashes(@$_REQUEST['address']);
			dbQuery("insert into addressbook (name,preferred_languages,notes,address,cdate) values ('$name','$languages','$notes','$address',now())");
			$id=dbOne('select last_insert_id() as id','id');
			$js='parent.hide_addressbook_entry_form(true);';
		}
		else{
			$js='alert("'.addslashes(join("\n",$errors)).'");';
		}
		echo '<script type="text/javascript">'.$js.'</script>';
		exit;
	// }
	case 'delete_addressbook_entry': // {
		$id=(int)@$_REQUEST['id'];
		dbQuery("delete from addressbook where id=$id");
		dbQuery("delete from addressbook_vars where addressbook_id=$id");
		$retval="{'success':1}";
		break;
	// }
	case 'edit_addressbook_entry_field': // {
		$id=(int)@$_REQUEST['id'];
		$field_name=addslashes(@$_REQUEST['field_name']);
		$value=addslashes(@$_REQUEST['value']);
		switch($field_name){
			case 'name': case 'address': case 'notes': // {
				dbQuery("update addressbook set $field_name='$value' where id=$id");
				$retval="{'id':$id,'field_name':'$field_name','success':1,'value':'$value'}";
				break;
			// }
			default: $retval="{'id':$id,'field_name':'$field_name','success':0,'error':'Field \"$field_name\" not recognised'}";
		}
		break;
	// }
	case 'get_addressbook_entry_form': // {
		$retval='<form id="addressbook_entry_form" method="post" action="/addressbook-ajax.php" target="iframe">'
			.'<iframe style="width:1px;height:1px;visibility:hidden" name="iframe" src="about:blank"></iframe>'
			.'<input type="hidden" name="action" value="add_addressbook_entry" />'
			.'<table>'
			.'<tr><th>Name</th><td><input name="name" /></td>'
			.'<th>Preferred Languages</th><td><input name="preferred_languages" /></td></tr>'
			.'<tr><th>Address</th><td><textarea class="fullsize" name="address"></textarea></td>'
			.'<th>Notes</th><td><textarea class="fullsize" name="notes"></textarea></td></tr>';
		// TODO: custom fields go here
		$retval.='<tr><th colspan="3"><input type="submit" value="add contact" /></th><td><a href="javascript:hide_addressbook_entry_form()">cancel</a></td></tr></table></form>';
		break;
	// }
	default: $retval='<span>huh? an error occurred.</span>';
}

echo $retval;
